//
//  AppController.m
//  Sofia
//
//  Created by Anton Chebotaev on 19/11/08.
//  Copyright 2008 IFMO. All rights reserved.
//

#import "SFAppController.h"

#import "MBPreferencesController.h"
#import "SFGeneralViewController.h"
#import "SFAccountsViewController.h"
#import "SFMusicViewController.h"
#import "SFTagsViewController.h"

#import "SFMusicFormatToken.h"


@implementation SFAppController
+ (void)initialize
{
    // Create a dictionary for default values
    NSMutableDictionary *defaultValues = [NSMutableDictionary dictionary];
		
    // Archive accounts object
    NSData *userAccountsAsData = [NSKeyedArchiver archivedDataWithRootObject:
						   [NSMutableArray array]];
	NSData *musicFormatAsData = [NSKeyedArchiver archivedDataWithRootObject:
								 [NSArray arrayWithObjects:
								  [SFMusicFormatToken tokenWithString:@"♪ "],
								  [SFMusicFormatToken tokenWithString:SFAArtistToken],
								  [SFMusicFormatToken tokenWithString:@" - "],
								  [SFMusicFormatToken tokenWithString:SFATitleToken],nil
								 ]];
	
    // Put defaults in the dictionary
    [defaultValues setObject:@"Test"
					  forKey:SFATextValue];
    [defaultValues setObject:[NSNumber numberWithInt:-1]
					  forKey:SFADefaultAccountNumber];
    [defaultValues setObject:[NSNumber numberWithBool:YES]
                      forKey:SFAOpenUntitled];
    [defaultValues setObject:userAccountsAsData
                      forKey:SFAAccouns];
    [defaultValues setObject:@""
                      forKey:SFATextValue];
    [defaultValues setObject:musicFormatAsData
                      forKey:SFAMusicFormat];
	
    // Register the dictionary of defaults if there was nothing
    NSLog(@"Registering defaults: %@", defaultValues);
    [[NSUserDefaults standardUserDefaults] registerDefaults: defaultValues];
	
	// preparing MBPreferencesController
	SFGeneralViewController *general = [[SFGeneralViewController alloc] initWithNibName:@"PreferencesGeneral" bundle:nil];
	SFAccountsViewController *accounts = [[SFAccountsViewController alloc] initWithNibName:@"PreferencesAccounts" bundle:nil];
	SFAccountsViewController *music = [[SFMusicViewController alloc] initWithNibName:@"PreferencesMusic" bundle:nil];
	SFAccountsViewController *tags = [[SFTagsViewController alloc] initWithNibName:@"PreferencesTags" bundle:nil];
	[[MBPreferencesController sharedController] setModules:[NSArray arrayWithObjects:general, accounts, music, tags, nil]];
	[tags release];
	[general release];
	[accounts release];
	[music release];
	
	NSLog(@"%@", [[NSApp mainMenu] description]);
}

- (BOOL)applicationShouldOpenUntitledFile:(NSApplication *)sender
{
    NSLog(@"applicationShouldOpenUntitledFile:");
    return [[NSUserDefaults standardUserDefaults] boolForKey:SFAOpenUntitled];
}

- (IBAction)showPreferences:(id)sender
{
    [[MBPreferencesController sharedController] showWindow:sender];
}

- (IBAction)logIn:(id)sender
{
	// Load UserAcounts
    NSData *userAccountsAsData = [[NSUserDefaults standardUserDefaults] objectForKey:SFAAccouns];
    NSArray *accounts = [NSMutableArray arrayWithArray:[NSKeyedUnarchiver unarchiveObjectWithData:userAccountsAsData]];	
	// Load DefaultAccountNumber
	int defaultAccountNumber = [[NSUserDefaults standardUserDefaults] integerForKey:SFADefaultAccountNumber];
	NSString *username = [[accounts objectAtIndex:defaultAccountNumber] username];
	NSString *password = [[accounts objectAtIndex:defaultAccountNumber] password];
	LJAccount *account = [[LJAccount alloc] initWithUsername:username];

NS_DURING
	[[account server] setURL:[NSURL URLWithString:@"http://www.livejournal.com"]];
	[account loginWithPassword:password];
	
	if ([account loginMessage]) {
		NSRunAlertPanel(@"Message from the Server", // *title,
						[account loginMessage], // *msg,
						nil, // *defaultButton,
						nil, // *alternateButton,
						nil); // *otherButton, ...);
	}
	else
	{
		NSRunAlertPanel(@"Congratulations", // *title,
						@"access to antonche's livejournal granted", // *msg,
						@"Cheers!", // *defaultButton,
						nil, // *alternateButton,
						nil); // *otherButton, ...);
		
	}
NS_HANDLER
	NSRunAlertPanel(@"SimpleJournal Error", // *title,
					[localException reason], // *msg,
					nil, // *defaultButton,
					nil, // *alternateButton,
					nil); // *otherButton, ...);
	[account release];
	account = nil;
NS_ENDHANDLER
	
	
	
/*    NS_DURING
	[account release];
	username = [usernameField stringValue];
	account = [[LJAccount alloc] initWithUsername:username];
	urlString = [@"http://" stringByAppendingString:[hostField stringValue]];
	[[account server] setURL:[NSURL URLWithString:urlString]];
	[account loginWithPassword:[passwordField stringValue]];
	[NSApp endSheet:loginPanel];
	[loginPanel orderOut:nil];
	loggingIn = NO;
	// Setup Journal PopUp
	[journalPopUp setMenu:[account journalMenu]];
	[journalPopUp selectItemAtIndex:0];
	[journalPopUp setEnabled:YES];
	// Setup Web Menu
	[self updateWebMenu];
	// Setup CheckFriends
	//[account setCheckFriendsInterval:60];
	//[account startCheckingFriends];
	// Set Window Title
	[mainWindow setTitle:[account fullname]];
	[self newEntry:nil];
	// Show Login Message
	if ([account loginMessage]) {
		NSRunAlertPanel(@"Message from the Server", // *title,
						[account loginMessage], // *msg,
						nil, // *defaultButton,
						nil, // *alternateButton,
						nil); // *otherButton, ...);
	}
    NS_HANDLER
	NSRunAlertPanel(@"SimpleJournal Error", // *title,
					[localException reason], // *msg,
					nil, // *defaultButton,
					nil, // *alternateButton,
					nil); // *otherButton, ...);
	[account release];
	account = nil;
    NS_ENDHANDLER
 */
}
@end
